import mysql from 'mysql'
import config from '../config/mysql-config'
let pool,configs;

function setConfig(options) {
    configs = Object.assign(config,options)
}

function openConnect() {
    pool = mysql.createPool(config);
}

function closeConnect() {
    pool.close();
}

function execute(sql,params) {
    return new Promise((resolve,reject) => {
        try {
            pool.getConnection((err, conn) => {
                if (err) {
                    return reject(err);
                }
                conn.query(sql, params, (err, res) => {
                    conn.release();
                    if (err) {
                        return reject(err);
                    }
                    if (res['affectedRows'] > 0) {
                        return resolve(res['affectedRows']);
                    }
                })
            });
        }catch (e) {
            reject(e);
        }
    })
}

function query(sql,params) {
    return new Promise((resolve,reject) => {
        try {
            pool.getConnection((err, conn) => {
                if (err) {
                    return reject(err);
                }
                conn.query(sql, params, (err, res) => {
                    conn.release();
                    if (err) {
                        return reject(err);
                    }
                    resolve(res);
                })
            });
        }catch (e) {
            reject(e);
        }
    })
}

export default {
    setConfig,
    openConnect,
    closeConnect,
    execute,
    query
}